package com.piggy.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.piggy.common.core.enums.CacheKeyEnums;
import com.piggy.common.redis.cache.CacheUtils;
import com.piggy.common.satoken.utils.SecurityUtils;
import com.piggy.sys.api.domain.SysClientDetails;
import com.piggy.sys.mapper.SysClientDetailsMapper;
import com.piggy.sys.service.ISysClientDetailsService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 终端配置Service业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysClientDetailsServiceImpl extends ServiceImpl<SysClientDetailsMapper, SysClientDetails>  implements ISysClientDetailsService
{

    /**
     * 查询终端配置
     *
     * @param clientId 终端配置ID
     * @return 终端配置
     */
    @Override
    public SysClientDetails selectSysClientDetailsById(String clientId)
    {
        return getCache(clientId);
    }

    /**
     * 查询终端配置列表
     *
     * @param sysClientDetails 终端配置
     * @return 终端配置
     */
    @Override
    public List<SysClientDetails> selectSysClientDetailsList(SysClientDetails sysClientDetails)
    {
        return this.list(buildQueryWrapper(sysClientDetails));
    }

    /**
     * 新增终端配置
     *
     * @param sysClientDetails 终端配置
     * @return 结果
     */
    @Override
    public int insertSysClientDetails(SysClientDetails sysClientDetails)
    {
        if (StrUtil.isBlank(sysClientDetails.getScope())) {
            sysClientDetails.setScope("server");
        }
        sysClientDetails.setClientSecret(SecurityUtils.encryptPassword(sysClientDetails.getOriginSecret()));
        int insert = baseMapper.insertSysClientDetails(sysClientDetails);
        cache(sysClientDetails);
        return insert;
    }

    /**
     * 修改终端配置
     *
     * @param sysClientDetails 终端配置
     * @return 结果
     */
    @Override
    public int updateSysClientDetails(SysClientDetails sysClientDetails)
    {
        sysClientDetails.setClientSecret(SecurityUtils.encryptPassword(sysClientDetails.getOriginSecret()));
        int update = baseMapper.updateSysClientDetails(sysClientDetails);
        cache(sysClientDetails);
        return update;
    }

    /**
     * 批量删除终端配置
     *
     * @param clientIds 需要删除的终端配置ID
     * @return 结果
     */
    @Override
    public int deleteSysClientDetailsByIds(String[] clientIds)
    {
        removeCache(clientIds);
        return baseMapper.deleteSysClientDetailsByIds(clientIds);
    }

    private LambdaQueryWrapper<SysClientDetails> buildQueryWrapper(SysClientDetails bo) {
        LambdaQueryWrapper<SysClientDetails> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getResourceIds()), SysClientDetails::getResourceIds, bo.getResourceIds());
        lqw.eq(StrUtil.isNotBlank(bo.getClientSecret()), SysClientDetails::getClientSecret, bo.getClientSecret());
        lqw.eq(StrUtil.isNotBlank(bo.getScope()), SysClientDetails::getScope, bo.getScope());
        lqw.eq(StrUtil.isNotBlank(bo.getAuthorizedGrantTypes()), SysClientDetails::getAuthorizedGrantTypes, bo.getAuthorizedGrantTypes());
        lqw.eq(StrUtil.isNotBlank(bo.getWebServerRedirectUri()), SysClientDetails::getWebServerRedirectUri, bo.getWebServerRedirectUri());
        lqw.eq(StrUtil.isNotBlank(bo.getAuthorities()), SysClientDetails::getAuthorities, bo.getAuthorities());
        lqw.eq(bo.getAccessTokenValidity() != null, SysClientDetails::getAccessTokenValidity, bo.getAccessTokenValidity());
        lqw.eq(bo.getRefreshTokenValidity() != null, SysClientDetails::getRefreshTokenValidity, bo.getRefreshTokenValidity());
        lqw.eq(StrUtil.isNotBlank(bo.getAdditionalInformation()), SysClientDetails::getAdditionalInformation, bo.getAdditionalInformation());
        lqw.eq(bo.getAutoapprove() != null, SysClientDetails::getAutoapprove, bo.getAutoapprove());
        lqw.eq(StrUtil.isNotBlank(bo.getOriginSecret()), SysClientDetails::getOriginSecret, bo.getOriginSecret());
        lqw.eq(bo.getClientStatus() != null, SysClientDetails::getClientStatus, bo.getClientStatus());
        return lqw;
    }

    /**
     * cache redis
     */
    private void cache(SysClientDetails sysClientDetails) {
        if (Objects.isNull(sysClientDetails)) {
            return;
        }
        String key = CacheKeyEnums.SysClient.getKey(sysClientDetails.getClientId());
        CacheUtils.cache(sysClientDetails, key);
    }

    private SysClientDetails getCache(String clientId) {
        String key = CacheKeyEnums.SysClient.getKey(clientId);
        return CacheUtils.getCache(key, SysClientDetails.class, () -> {
            SysClientDetails details = baseMapper.selectSysClientDetailsById(clientId);
            cache(details);
            return details;
        });
    }

    private void removeCache(String[] clientIds) {
        if (clientIds!=null && clientIds.length>0) {
            for (String client : clientIds) {
                String key = CacheKeyEnums.SysClient.getKey(client);
                CacheUtils.remove(key);
            }
        }
    }

}
